package com.yuanzheng.config;

import com.yuanzheng.pojo.User;
import com.yuanzheng.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

/**
 * @author yuanzheng
 * @date 2020/4/15-13:19
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 权限---授予
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //authorizationInfo.addStringPermission("user:add");

        // 获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        List<String> permissionsList = Arrays.asList(currentUser.getPerms().split(","));
        authorizationInfo.addStringPermissions(permissionsList);

        return authorizationInfo;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 认证---验证

        // 数据库中取用户名和密码进行比对
        //String name = "123";
        //String pwd = "123";
        //UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 用户认证
        /*if (!token.getUsername().equals(name)) {
            return null;  // UnknownAccountException
        }*/

        // 用户认证
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryUserByName(token.getUsername());
        if (user == null) {
            return null;
        }

        // 密码认证
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
